import axios from "axios";
const BaseUrl = "/api";
const Instance = axios.create({ baseURL: BaseUrl });
import { ElMessage } from "element-plus";
import { userTokenStore } from "@/store/userTokenStore.js";
import router from "@/router";

Instance.interceptors.request.use(
  (config) => {
    const token = userTokenStore().token;
    if (token) {
      config.headers.setAuthorization(token);
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  },
);

Instance.interceptors.response.use(
  (result) => {
    if (result.data.code === 0) {
      return result.data;
    } else{
        switch (result.data.code) {
            case 40000:
            {
                console.log(result.data)
                ElMessage.error(JSON.stringify(result.data.data).replace(/^"+|"+$/g, ''));
                break
            }
            case 40100:{
                ElMessage.error("请重新登录");
                router.push("/login").then(r=>{return Promise.reject(result.data);})
                break
            }
            case 40101:{
                ElMessage.error("权限不足");
                router.push("/NoAuth").then(r => { return Promise.reject(result.data);});
                break
            }
            case 40400:{
                ElMessage.error("请求资源不存在");
                break;
            }
            case 40300:{
                ElMessage.error("禁止访问");
                break;
            }
            case 50000:{
                ElMessage.error("服务器错误");
                break;
            }
            default:{
                ElMessage.error("未知错误");
                break;
            }
        }
        return Promise.reject(result.data);
    }
  },
  (error) => {
    if (error.status === 401) {
      ElMessage.error("请先登录!");
      router.push("/login");
    } else {
      ElMessage.error( "操作失败!");
      return Promise.reject(error);
    }
  },
);

export default Instance;
